package user

import (
	"fmt"

	"gitlab.local/DO-module/new-filemanage-module/src/core/sqlitedb/sqlitemodel"
	"gitlab.local/golibrary/user"
	"sort"
	"strings"
)

func (u *User) GroupList(start, limit int) (result []Group, err error) {
	result = make([]Group, 0)
	groupList := make([]sqlitemodel.GroupTable, 0)
	db := u.liteDb.DbGet()
	tx := db.Table("user_table").Where("password=?", "group")
	if limit > 0 {
		tx = tx.Limit(limit).Offset(start)
	}
	err = tx.Find(&groupList).Error
	for _, group := range groupList {
		groupItem := Group{
			Description: group.Remarks,
			IsNvr:       group.IsNvr,
		}
		groupItem.Name = strings.TrimPrefix(group.Username, "@")
		lookup, err := user.LookupGroup(groupItem.Name)
		if err != nil {
			fmt.Println(err)
			continue
		}
		groupItem.Disabled = u.isSystemGroup(groupItem.Name)
		//获取用户id
		groupItem.Gid = lookup.Gid
		groupItem.UserList = u.GetUsersByGroup(groupItem.Name)
		result = append(result, groupItem)
	}
	sort.Sort(GroupSlice(result))
	return
}

// 判断是否是系统保留用户(前端表现为不可更名和删除)
func (u *User) isSystemGroup(name string) bool {
	if name == "admin" || name == "allusers" || name == "media" {
		return true
	}
	return false
}
